package com.xiangban.springTask;

import com.xiangban.dao.AccompanyMapper;
import com.xiangban.model.UserAccompany;
import com.xiangban.model.dto.AccompanyInviteDto;
import com.xiangban.model.dto.UserAccompanyDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 每日00:00:00计算更新陪诊员星级
 *
 * @Author Mr. MaYaYun
 * @Data 2021/12/15 11:26
 */
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class UserAccompanyGrade {

    private static Logger LOGGER = LoggerFactory.getLogger(UserAccompanyGrade.class);

    @Autowired
    private AccompanyMapper accompanyMapper;


    //3.添加定时任务
    @Scheduled(cron = "0 0 0 * * ?")
    //或首次延迟指定时间后执行直接指定时间间隔，例如：仅第一次程序开始是延迟10秒后 然后每间隔5秒开始执行程序一次
    //@Scheduled(initialDelay = 10000, fixedRate=5000)
    private void configureTasks() {
        LOGGER.info("执行静态定时任务时间开始: " + LocalDateTime.now());
        //计算获取陪诊员星级
        List<UserAccompanyDto> grade = accompanyMapper.getGrade();
        for (UserAccompanyDto userAccompanyDto : grade) {
            Integer accompanyId = userAccompanyDto.getAccompanyId();
            BigDecimal avgGrade = userAccompanyDto.getAvgGrade();
            int intGrade = avgGrade.setScale(0, BigDecimal.ROUND_HALF_UP).intValue();

            //修改陪诊员星级
            UserAccompany userAccompany = new UserAccompany();
            userAccompany.setAccompanyId(accompanyId);
            userAccompany.setGrade(intGrade);
            accompanyMapper.updateGradeByAccompanyId(userAccompany);
        }
        LOGGER.info("执行静态定时任务时间结束: " + LocalDateTime.now());
    }
}
